﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using System.Collections.ObjectModel;
using AtletIS.Shared.Data;
using AtletIS.Shared.Entities;
using System.Windows.Forms;

namespace AtletIS.Shared.Helpers
{
    public static class SignupsListHelper
    {
        private static DataTable dtDisciplineList;
        private static DataTable dtPerformances;

        /// <summary>
        ///  Vygeneruje HTML zoznam s počtami prihlásených pretekárov pre dané preteky
        /// </summary>
        public static void HtmlSignupCountList(CompetitionEntity competition)
        {
            string htmlFilePath = HtmlHelper.GetNewHtmlFileName("(P) " + competition.Name);
            StreamWriter sw = new StreamWriter(htmlFilePath, false, Encoding.Default);
            
            try
            {

                HtmlHelper.PrintHtmlHead(sw, "AtletIS");

                sw.WriteLine("<body>");

                HtmlHelper.PrintHeader(sw, "Počty prihlášok", Globals.ActiveCompetition);

                // Get discipline list
                dtDisciplineList = DatabaseHelper.GetDisciplineListByCompetitionIdActive(competition.ID); // taDisciplineList.GetByCompetitionId(competition.ID);

                //Printing
                sw.WriteLine("<table class=\"main-table\">");
                
                sw.WriteLine("<tr height=\"30\" bgcolor=\"#D8D8D8\">");
                sw.WriteLine("  <th>#</th>");
                sw.WriteLine("  <th>Názov disciplíny</th>");
                sw.WriteLine("  <th>Počet prihlášok</th>");
                sw.WriteLine("</tr>");

                if (dtDisciplineList.Rows.Count > 0)
                {
                    int count = 1;
                    foreach (DataRow drDisciplineList in dtDisciplineList.Rows)
                    {
                        dtPerformances = DatabaseHelper.GetPerformancesByDisciplineListId(Convert.ToInt32(drDisciplineList["ID"])); 

                        int signed = dtPerformances.Rows.Count;

                        if (count % 2 == 1)
                            sw.WriteLine("<tr>");
                        else
                            sw.WriteLine("<tr bgcolor=\"#CFECEC\">");

                        sw.WriteLine("  <td align=\"center\"> " + drDisciplineList["ID"].ToString() + "</td>");
                        sw.WriteLine("  <td> " + drDisciplineList["Name"].ToString() + "</td>");
                        sw.WriteLine("  <td align=\"center\"> " + signed.ToString() + "</td>");
                        sw.WriteLine("</tr>");
                        count += 1;
                    }
                }

                sw.WriteLine("</table>");
                sw.WriteLine();

                HtmlHelper.PrintFooter(sw);

                sw.WriteLine("</body>");
                sw.WriteLine("</html>");

                sw.Close();
                sw.Dispose();

                WordHelper.CreateWordFromHtml(htmlFilePath);

            }
            catch (Exception ex)
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }

                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        /// <summary>
        ///  Vygeneruje HTML zoznam prihlásených pretekárov podľa disciplín
        /// </summary>
        public static void HtmlSignupListForDisciplines(CompetitionEntity competition)
        {
            string htmlFilePath = HtmlHelper.GetNewHtmlFileName("(P) " + competition.Name);
            StreamWriter sw = new StreamWriter(htmlFilePath, false, Encoding.Default);
            
            try
            {
                HtmlHelper.PrintHtmlHead(sw, "AtletIS");

                sw.WriteLine("<body>");

                HtmlHelper.PrintHeader(sw, "Prihlášky po disciplínach", Globals.ActiveCompetition);

                // Get Discipline List
                dtDisciplineList = DatabaseHelper.GetDisciplineListByCompetitionIdActive(competition.ID); // taDisciplineList.GetByCompetitionId(competition.ID);

                if (dtDisciplineList.Rows.Count > 0)
                {
                    foreach (DataRow drDisciplineList in dtDisciplineList.Select(null, "Order"))
                    {
                        DisciplineListEntity discipline = DisciplineListHelper.ConvertToEntity(drDisciplineList);
                        dtPerformances = DatabaseHelper.GetPerformancesByDisciplineListId(Convert.ToInt32(drDisciplineList["ID"])); 

                        if (dtPerformances.Rows.Count > 0)
                        {
                            sw.WriteLine("<h3>" + discipline.Name + "  </h3>");
                            sw.WriteLine("<table class=\"main-table\">");

                            #region Print table header

                            sw.WriteLine("<tr height=\"30\" bgcolor=\"#D8D8D8\">");
                            sw.WriteLine("  <th width=\"30\">Št.č.  </th>");
                            sw.WriteLine("  <th width=\"30\"></th>");

                            sw.WriteLine("  <th>Meno   </th>");
                            sw.WriteLine("  <th>Nar.   </th> ");

                            if (Globals.ActiveCompetition.ClubsCountries == true)
                                sw.WriteLine("  <th>Klub   </th>");
                            else
                                sw.WriteLine("  <th>Krajina   </th>");

                            sw.WriteLine("  <th width=\"60\">SB</th>");
                            sw.WriteLine("  <th width=\"60\">PB</th>");
                            sw.WriteLine("</tr>");

                            #endregion

                            #region Sorting

                            string sSort;
                            switch (Convert.ToInt32(drDisciplineList["DisciplineCode"]))
                            {
                                case Globals.SprintCode:
                                case Globals.LongRunCode:
                                    foreach (DataRow dr in dtPerformances.Rows)
                                    {
                                        if (Convert.ToInt32(dr["SB"]) == 0)
                                            dr["SB"] = int.MaxValue;

                                        if (Convert.ToInt32(dr["PB"]) == 0)
                                            dr["PB"] = int.MaxValue;
                                    }
                                    sSort = "Lane, SB ASC, PB ASC, StartNumber, Surname";
                                    break;

                                case Globals.MarathonCode:
                                    sSort = "StartNumber, Surname";
                                    break;

                                default:
                                    sSort = "SB DESC, PB DESC, StartNumber, Surname";
                                    break;
                            }

                            #endregion

                            #region Print competitors

                            int count = 1;
                            foreach (DataRow dr in dtPerformances.Select(null, sSort))
                            {
                                if (count % 2 == 1)
                                    sw.WriteLine("<tr>");
                                else
                                    sw.WriteLine("<tr bgcolor=\"#CFECEC\">");

                                if (Convert.ToInt32(dr["StartNumber"]) == 0)
                                    sw.WriteLine("  <td align=\"center\"></td>");
                                else
                                    sw.WriteLine("  <td align=\"center\">(" + dr["StartNumber"] + ")</td>");

                                sw.WriteLine("  <td align=\"center\">" + PrintHelper.PrintFlagImage(dr) + "</td>");
                                
                                if (discipline.Relay)
                                {
                                    sw.WriteLine("  <td>" + PrintHelper.PrintRelayName(dr, competition.ClubsCountries) + "</td>");
                                    sw.WriteLine("  <td></td>");
                                }
                                else
                                {
                                    sw.WriteLine("  <td>" + PrintHelper.PrintName(dr) + "</td>");
                                    sw.WriteLine("  <td align=\"center\">" + PrintHelper.PrintBirthdate(Convert.ToDateTime(dr["Birthdate"])) + "</td>");
                                }

                                sw.WriteLine("  <td>" + 
                                    PrintHelper.PrintClubCountry(Globals.ActiveCompetition.ClubsCountries, dr["Club"].ToString(), dr["ClubName"].ToString(), dr["CountryId"].ToString(), dr["CountryName"].ToString()) + "</td>");

                                if (Convert.ToInt32(dr["SB"]) == 0 | Convert.ToInt32(dr["SB"]) == int.MaxValue)
                                    sw.WriteLine("  <td></td>");
                                else
                                    sw.WriteLine("  <td align=\"center\">" + PrintHelper.PrintResult(dr["SB"].ToString(), Convert.ToInt32(dr["DisciplineCode"])) + "</td>");

                                if (Convert.ToInt32(dr["PB"]) == 0 | Convert.ToInt32(dr["PB"]) == int.MaxValue)
                                    sw.WriteLine("  <td></td>");
                                else
                                    sw.WriteLine("  <td align=\"center\">" + PrintHelper.PrintResult(dr["PB"].ToString(), Convert.ToInt32(dr["DisciplineCode"])) + "</td>");

                                sw.WriteLine("</tr>");
                                count += 1;
                            }

                            #endregion

                            sw.WriteLine("</table>");

                            #region Discipline info table

                            sw.WriteLine("<table class=\"extra\">");
                            sw.WriteLine("<tr>");
                            sw.WriteLine("  <td width=\"50\"></td>");
                            sw.WriteLine("  <td width=\"120\"> Počet pretekárov: " + dtPerformances.Rows.Count.ToString() + "</td>");
                            sw.WriteLine("  <td width=\"100\"> Čas štartu: " + discipline.StartTime.ToShortTimeString() + "</td>");
                            sw.WriteLine("</tr>");
                            sw.WriteLine("</table>");

                            #endregion
                        }
                    }
                }

                HtmlHelper.PrintFooter(sw);

                sw.WriteLine("</body>");
                sw.WriteLine("</html>");

                sw.Close();
                sw.Dispose();

                WordHelper.CreateWordFromHtml(htmlFilePath);
            }
            catch (Exception ex)
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }

                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        /// <summary>
        ///  Vygeneruje HTML zoznam prihlásených pretekárov podľa klubov
        /// </summary>
        public static void HtmlSignupListForClubs(CompetitionEntity competition)
        {
            string htmlFilePath = HtmlHelper.GetNewHtmlFileName("(P) " + competition.Name);
            StreamWriter sw = new StreamWriter(htmlFilePath, false, Encoding.Default);
            
            try
            {
                HtmlHelper.PrintHtmlHead(sw, "AtletIS");

                sw.WriteLine("<body>");

                HtmlHelper.PrintHeader(sw, "Prihlášky po kluboch", Globals.ActiveCompetition);

                // Get Clubs
                DataTable dtClubs = DatabaseHelper.GetPerformancesDistinctClubs(competition.ID); 

                if (dtClubs.Rows.Count > 0)
                {
                    foreach (DataRow drClub in dtClubs.Rows)
                    {
                        // Print discipline header
                        sw.WriteLine("<h3>" + drClub["ClubName"].ToString() + "  </h3>");
                        sw.WriteLine("<table class=\"main-table\">");
                        
                        #region Print header

                        sw.WriteLine("<tr height=\"30\" bgcolor=\"#D8D8D8\">");
                        sw.WriteLine("  <th width=\"30\">Št.č.</th>");
                        sw.WriteLine("  <th>          </th>");
                        sw.WriteLine("  <th>Meno      </th>");
                        sw.WriteLine("  <th>Nar.      </th>");
                        sw.WriteLine("  <th>Disciplína</th>");
                        sw.WriteLine("  <th width=\"60\">SB</th>");
                        sw.WriteLine("  <th width=\"60\">PB</th>");
                        sw.WriteLine("</tr>");

                        #endregion

                        dtPerformances = DatabaseHelper.GetPerformancesByCompetitionIdClubId(competition.ID, drClub["Club"].ToString());

                        #region Print performances

                        int count = 1;
                        foreach (DataRow drPerformance in dtPerformances.Select(null, "Surname, FirstName"))
                        {
                            PrintClubOrCountryRow(competition, drPerformance, sw, ref count);
                        }

                        #endregion

                        sw.WriteLine("</table>");

                        #region Discipline info table

                        int competitorsCount = 0, startsCount = 0;
                        int prevCompetitorId = 0;

                        if (dtPerformances != null && dtPerformances.Rows.Count > 0)
                        {
                            foreach (DataRow dr in dtPerformances.Select(null, "CompetitorId"))
                            {
                                if (dr["CompetitorId"] != DBNull.Value && Convert.ToInt32(dr["CompetitorId"]) > 1)
                                {
                                    if (Convert.ToInt32(dr["CompetitorId"]) != prevCompetitorId)
                                        competitorsCount += 1;

                                    prevCompetitorId = Convert.ToInt32(dr["CompetitorId"]);
                                    startsCount += 1;
                                }
                            }
                        }

                        sw.WriteLine("<table class=\"extra\">");
                        sw.WriteLine("<tr>");
                        sw.WriteLine("  <td width=\"50\"></td>");
                        sw.WriteLine("  <td width=\"120\"> Počet reg. pretekárov/štartov: " + competitorsCount.ToString() + "/" + startsCount.ToString() + "</td>");
                        sw.WriteLine("  <td width=\"100\"> </td>");
                        sw.WriteLine("</tr>");
                        sw.WriteLine("</table>");

                        #endregion
                    }
                }

                HtmlHelper.PrintFooter(sw);

                sw.WriteLine("</body>");
                sw.WriteLine("</html>");

                sw.Close();
                sw.Dispose();

                WordHelper.CreateWordFromHtml(htmlFilePath);
            }
            catch (Exception ex)
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }

                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        /// <summary>
        ///  Vygeneruje HTML zoznam prihlásených pretekárov podľa krajín
        /// </summary>
        public static void HtmlSignupListForCountries(CompetitionEntity competition)
        {
            string htmlFilePath = HtmlHelper.GetNewHtmlFileName("(P) " + competition.Name);
            StreamWriter sw = new StreamWriter(htmlFilePath, false, Encoding.Default);
            
            try
            {
                HtmlHelper.PrintHtmlHead(sw, "AtletIS");

                sw.WriteLine("<body>");

                HtmlHelper.PrintHeader(sw, "Prihlášky po krajinách", Globals.ActiveCompetition);

                // Get Countries
                DataTable dtCountries = DatabaseHelper.GetPerformancesDistinctCountries(competition.ID); 

                if (dtCountries.Rows.Count > 0)
                {
                    foreach (DataRow drCountry in dtCountries.Select(null, "Name"))
                    {
                        dtPerformances = DatabaseHelper.GetPerformancesByCompetitionIdCountryId(competition.ID, drCountry["CountryId"].ToString()); 

                        if (dtPerformances.Rows.Count > 0)
                        {

                            // Print discipline header
                            sw.WriteLine("<h3>" + PrintHelper.PrintFlagImage(drCountry) + " " + drCountry["Name"].ToString() + " </h3>");
                            sw.WriteLine("<table class=\"main-table\">");

                            #region Print header

                            sw.WriteLine("<tr height=\"30\" bgcolor=\"#D8D8D8\">");
                            sw.WriteLine("  <th width=\"30\">St.num.</th>");
                            sw.WriteLine("  <th width=\"30\"></th>");
                            sw.WriteLine("  <th>Name          </th>");
                            sw.WriteLine("  <th>Year          </th>");
                            sw.WriteLine("  <th>Discipline    </th>");
                            sw.WriteLine("  <th width=\"60\" >SB            </th>");
                            sw.WriteLine("  <th width=\"60\" >PB            </th>");
                            sw.WriteLine("</tr>");

                            #endregion

                            #region Print performances
                            
                            int count = 1;
                            foreach (DataRow drPerformance in dtPerformances.Select(null, "Order, StartNumber, Surname, FirstName"))
                            {
                                PrintClubOrCountryRow(competition, drPerformance, sw, ref count);
                            }

                            #endregion

                            sw.WriteLine("</table>");

                            #region Discipline info table

                            sw.WriteLine("<table class=\"extra\">");
                            sw.WriteLine("<tr>");
                            sw.WriteLine("  <td width=\"50\"></td>");
                            sw.WriteLine("  <td width=\"120\"> Počet pretekárov: " + dtPerformances.Rows.Count.ToString() + "</td>");
                            sw.WriteLine("  <td width=\"100\"></td>");
                            sw.WriteLine("</tr>");
                            sw.WriteLine("</table>");

                            #endregion
                        }
                    }
                }

                HtmlHelper.PrintFooter(sw);

                sw.WriteLine("</body>");
                sw.WriteLine("</html>");

                sw.Close();
                sw.Dispose();

                WordHelper.CreateWordFromHtml(htmlFilePath);
            }
            catch (Exception ex)
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }

                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        private static void PrintClubOrCountryRow(CompetitionEntity competition, DataRow drPerformance, StreamWriter sw, ref int count)
        {
            if (count % 2 == 1)
                sw.WriteLine("<tr>");
            else
                sw.WriteLine("<tr bgcolor=\"#CFECEC\">");

            if (Convert.ToInt32(drPerformance["StartNumber"]) == 0)
                sw.WriteLine("  <td align=\"center\"></td>");
            else
                sw.WriteLine("  <td align=\"center\">(" + drPerformance["StartNumber"] + ")</td>");

            sw.WriteLine("  <td align=\"center\">" + PrintHelper.PrintFlagImage(drPerformance) + "</td>");

            if (Convert.ToBoolean(drPerformance["Relay"]))
            {
                sw.WriteLine("  <td>" + PrintHelper.PrintRelayName(drPerformance, competition.ClubsCountries) + "</td>");
                sw.WriteLine("  <td></td>");
            }
            else
            {
                sw.WriteLine("  <td>" + PrintHelper.PrintName(drPerformance) + "</td>");
                sw.WriteLine("  <td align=\"center\">" + PrintHelper.PrintBirthdate(Convert.ToDateTime(drPerformance["Birthdate"])) + "</td>");
            }

            // Discipline list name
            sw.WriteLine("  <td>" + drPerformance["Name"] + "</td>");

            if (Convert.ToInt32(drPerformance["SB"]) == 0)
                sw.WriteLine("  <td></td>");
            else
                sw.WriteLine("  <td align=\"center\">" + PrintHelper.PrintResult(drPerformance["SB"].ToString(), Convert.ToInt32(drPerformance["DisciplineCode"])) + "</td>");

            if (Convert.ToInt32(drPerformance["PB"]) == 0)
                sw.WriteLine("  <td></td>");
            else
                sw.WriteLine("  <td align=\"center\">" + PrintHelper.PrintResult(drPerformance["PB"].ToString(), Convert.ToInt32(drPerformance["DisciplineCode"])) + "</td>");

            sw.WriteLine("</tr>");
            count += 1;
        }

    }
}
